import Utils from "../common/Util";
import PropManager from "./PropManager";
import EventUtils from "../gmbox/EventUtils";

// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class FlyTrasureChest extends cc.Component {

    @property
    flyTargetY: number = 0;

    @property
    flyDuration: number = 0;

    @property
    stayTime = 0;

    @property(cc.Node)
    trasureChest: cc.Node = null;

    @property(cc.Label)
    timer: cc.Label = null;

    // LIFE-CYCLE CALLBACKS:

    public mTrasureChestIndex;

    private startTime = 0;

    private timeOut;

    onLoad() {
        this.trasureChest.runAction(this.getTrasureChestPathAction());
        Utils.addEventListener(this.trasureChest, this.onTrasureChestClick.bind(this));
    }

    private getTrasureChestPathAction() {
        var callback = cc.callFunc(this.onTrasureChestFlyEnd, this);
        var flyPath = cc.moveTo(this.flyDuration, cc.v2(this.trasureChest.x, this.flyTargetY)).easing(cc.easeCubicActionOut());
        return cc.sequence(flyPath, callback);
    }

    private onTrasureChestFlyEnd() {
        this.timer.node.active = true;
        this.startTime = new Date().getTime();
        this.TimeDown();
    }

    private onTrasureChestClick() {
        EventUtils.logEvent("click_trasure_chest", {
            index: this.mTrasureChestIndex
        })
        PropManager.getInstance().openTreasure();
        this.node.destroy();
    }

    private TimeDown() {
        var deltaTime = new Date().getTime() - this.startTime;
        var remainTime = this.stayTime * 1000 - deltaTime;
        if (remainTime <= 0) {
            this.node.destroy();
            return;
        }
        var d = new Date(remainTime);
        if (this.timer) {
            this.timer.string = this.addZero(d.getMinutes()) + ":" + this.addZero(d.getSeconds());
        }
        this.timeOut = setTimeout(() => {
            this.TimeDown();
        }, 500)
    }

    private addZero(m: number) {
        return m < 10 ? '0' + m : m;
    }

    start() {

    }

    onDestroy() {
        clearTimeout(this.timeOut)
    }

    // update (dt) {}
}
